﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Common.Utility;
using RuYiAdmin.Net.Entity.BusinessDTO.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Entity.CoreEntity;
using RuYiAdmin.Net.Service.BusinessService.Redis;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.Organization;
using RuYiAdmin.Net.WebApi.AppCode.ActionFilters;
using RuYiAdmin.Net.WebApi.AppCode.FrameworkBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.Controllers.SystemManagement
{
    /// <summary>
    /// 机构管理控制器
    /// </summary>
    public class OrganizationManagementController : BaseController<SysOrganization>
    {
        #region 属性及构造函数

        /// <summary>
        /// 机构接口实例
        /// </summary>
        private readonly IOrganizationService organizationService;

        /// <summary>
        /// Redis接口实例
        /// </summary>
        private readonly IRedisService redisService;

        /// <summary>
        /// AutoMapper实例
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="organizationService"></param>
        /// <param name="redisService"></param>
        /// <param name="mapper"></param>
        public OrganizationManagementController(IOrganizationService organizationService,
                                                IRedisService redisService,
                                                IMapper mapper) : base(organizationService)
        {
            this.organizationService = organizationService;
            this.redisService = redisService;
            this.mapper = mapper;
        }

        #endregion

        #region 查询机构列表

        /// <summary>
        /// 查询机构列表
        /// </summary>
        /// <returns>QueryResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("org:query:list")]
        public IActionResult Post(QueryCondition queryCondition)
        {
            var actionResult = this.organizationService.GetOrgTreeNodes();
            return Ok(actionResult);
        }

        #endregion

        #region 查询机构信息

        /// <summary>
        /// 查询机构信息
        /// </summary>
        /// <param name="orgId">机构编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{orgId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("org:query:list")]
        public IActionResult GetById(Guid orgId)
        {
            var actionResult = new Entity.CoreEntity.ActionResult();

            actionResult.HttpStatusCode = HttpStatusCode.OK;
            actionResult.Message = new String("OK");
            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            actionResult.Object = orgs.Where(t => t.Id == orgId).FirstOrDefault();

            return Ok(actionResult);
        }

        #endregion

        #region 新增机构信息

        /// <summary>
        /// 新增机构信息
        /// </summary>
        /// <param name="org">机构对象</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.AddEntity)]
        [Permission("org:add:entity")]
        public IActionResult Add([FromBody] SysOrganization org)
        {
            var actionResult = this.organizationService.Add(org);

            //数据一致性维护
            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            var orgDTO = mapper.Map<SysOrganizationDTO>(org);
            orgs.Add(orgDTO);
            this.redisService.Set(GlobalContext.SystemCacheConfig.OrgCacheName, orgs, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 编辑机构信息

        /// <summary>
        /// 编辑机构信息
        /// </summary>
        /// <param name="org">机构对象</param>
        /// <returns>ActionResult</returns>
        [HttpPut]
        [Log(OperationType.EditEntity)]
        [Permission("org:edit:entity")]
        public IActionResult Put([FromBody] SysOrganization org)
        {
            var actionResult = this.organizationService.Update(org);

            //数据一致性维护
            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            var old = orgs.Where(t => t.Id == org.Id).FirstOrDefault();
            orgs.Remove(old);
            var orgDTO = mapper.Map<SysOrganizationDTO>(org);
            orgs.Add(orgDTO);
            this.redisService.Set(GlobalContext.SystemCacheConfig.OrgCacheName, orgs, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 删除机构信息

        /// <summary>
        /// 删除机构信息
        /// </summary>
        /// <param name="orgId">对象编号</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{orgId}")]
        [Log(OperationType.DeleteEntity)]
        [Permission("org:del:entities")]
        public IActionResult Delete(Guid orgId)
        {
            if (this.Check(orgId))
            {
                return BadRequest("org contains users or sub orgs,can not be deleted.");
            }

            var actionResult = this.organizationService.Delete(orgId);

            //数据一致性维护
            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            var org = orgs.Where(t => t.Id == orgId).FirstOrDefault();
            orgs.Remove(org);
            this.redisService.Set(GlobalContext.SystemCacheConfig.OrgCacheName, orgs, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 批量删除机构

        /// <summary>
        /// 批量删除机构
        /// </summary>
        /// <param name="ids">编号数组</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{ids}")]
        [Log(OperationType.DeleteEntity)]
        [Permission("org:del:entities")]
        public IActionResult DeleteRange(String ids)
        {
            var array = StringUtil.GetGuids(ids);
            foreach (var item in array)
            {
                if (this.Check(item))
                {
                    return BadRequest("org contains users or sub orgs,can not be deleted.");
                }
            }

            var actionResult = this.organizationService.DeleteRange(array);

            //数据一致性维护
            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            foreach (var item in array)
            {
                var org = orgs.Where(t => t.Id == item).FirstOrDefault();
                orgs.Remove(org);
            }
            this.redisService.Set(GlobalContext.SystemCacheConfig.OrgCacheName, orgs, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 获取机构用户树

        /// <summary>
        /// 获取机构用户树
        /// </summary>
        /// <returns>QueryResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("role:query:list,user:query:list")]
        public IActionResult GetOrgUserTree()
        {
            var actionResult = this.organizationService.GetOrgUserTree();
            return Ok(actionResult);
        }

        #endregion

        #region 机构删除检测

        /// <summary>
        /// 机构删除检测
        /// </summary>
        /// <param name="orgId">机构编号</param>
        /// <returns>真假值</returns>
        private bool Check(Guid orgId)
        {
            var users = this.redisService.Get<List<SysUserDTO>>(GlobalContext.SystemCacheConfig.UserCacheName);
            users = users.Where(t => t.OrgId == orgId).ToList();

            var orgs = this.redisService.Get<List<SysOrganizationDTO>>(GlobalContext.SystemCacheConfig.OrgCacheName);
            var orgCount = orgs.Where(t => t.ParentId == orgId).Count();

            if (users.Count > 0 || orgCount > 0)
            {
                return true;
            }

            return false;
        }

        #endregion
    }
}
